import { View, Text, ScrollView,Icon } from "@tarojs/components";
import Taro, { useLoad } from "@tarojs/taro";
import "./index.scss";
import { useMemo, useState,useEffect } from "react";
import { request } from "../../utils/request";

export default function FamilyIns() {
  const mockInsList = [
    {
      id: "1",
      userName: "韩梅梅",
      insureName: "万户健康保（一级）2024",
      status: "保障中",
      insuredPerson: "李磊",
      money: "10000",
      amount: "50万",
      type: "健康险",
      time: "2024-01-01至2024-12-31",
    },
    {
      id: "2",
      userName: "小明",
      insureName: "万户健康保（一级）2025",
      status: "保障中",
      insuredPerson: "李磊",
      money: "10000",
      amount: "50万",
      type: "健康险",
      time: "2024-01-01至2024-12-31",
    },
    {
      id: "3",
      userName: "王多鱼",
      insureName: "万户健康保（一级）2025",
      status: "保障中",
      insuredPerson: "李磊",
      money: "10000",
      amount: "50万",
      type: "健康险",
      time: "2024-01-01至2024-12-31",
    },
  ];
  type insType = {
    endDate: string;
    goldCount: number;
    insuranceCoverage: string;
    insuranceDeductible: string;
    name: null | string;
    productName: string;
    productType: number;
    startDate: string;
    orderStatusCN:string;
  }
  type memeberType = {
    id: string;
    name: string;
    familyInsuranceDetailDTOList: insType[];
  }
  const [loading, setLoading] = useState(true);
  // 保险单裂变
  const [memberList, setMemberList] = useState<memeberType[]>([]);

  const router = Taro.getCurrentInstance().router as any;
  // console.log("router", router);
  // const memberId = router.params.memberId;
  // const memberId = '';
  // console.log('memberId:',memberId)
  const [selectedMemberId, setSelectedMemberId] = useState<string>('0');
  const [curInsList, setCurInsList] = useState<insType []>([])
  
 
  


  function handleMemberSelect(memeberId) {
    setSelectedMemberId(memeberId)
    console.log('memeberId:',memeberId)
    if(memeberId){
      
      let curMemeber = memberList.find(member=>{
        return member.id === memeberId
      })
      if(curMemeber){
        setCurInsList(curMemeber.familyInsuranceDetailDTOList)
      }
    }else {
      setCurInsList(memberList[0].familyInsuranceDetailDTOList)
    }
    // console.log('handleMemberSelect')
  }
  // function get
  async function getFamilyMemeberList() {
    return new Promise((resolve) => {
      request({
        url: `/api/points/family/getFamilyInsurance`,
        success: (data) => {
          data = data.filter(item=>{
            return item.familyInsuranceDetailDTOList.length > 0
          })
          data.forEach((item,index)=>{
            item.id = String(index)
            item.familyInsuranceDetailDTOList.forEach(ins=>{
              console.log('ins:',ins)
              ins.startDate = ins.startDate && ins.startDate.split(' ')[0] || ''
              ins.endDate = ins.endDate && ins.endDate.split(' ')[0] || ''
            })
            
          })
          console.log('data:',data)
          setMemberList(data);
          if(data && data.length > 0){
            setCurInsList(data[0].familyInsuranceDetailDTOList)
          }
        },
        complete() {
          resolve(true);
        },
      });
    });
  }

  function getProductTypeName(productType){
    let name = ''
    switch (productType) {
      case 1:
        name = '大病'
        break;
      case 2:
        name = '急病'
        break;
      case 3:
        name = '慢病'
        break;
      case 4:
        name = '体检服务'
        break;
      case 5:
        name = '绿通'
        break;
      default:
        name = '健康险'
        break;
    }
    return name
  }

  useLoad(async () => {
    console.log("Page loaded.");
    // 获取保险单裂变
    await getFamilyMemeberList();
    setLoading(false);
  });

  return (
    <View className="familyIns">
      {loading ? (
        <View className="loading">加载中...</View>
      ) : (
        <View className="content">
          <ScrollView scrollY>
            <ScrollView
              scrollX
              enableFlex
              style={{ display: "flex" }}
              showScrollbar={false}
            >
              <View className="memeber-list">
                {memberList.map((member) => {
                  return (
                    <View
                      className={[
                        "member-item",
                        selectedMemberId === member.id ? "selected" : "",
                      ].join(" ")}
                      key={member.id}
                      onClick={() => {
                        handleMemberSelect(member.id);
                      }}
                    >
                      <Text
                        className={[
                          "memeber-phone",
                          selectedMemberId === member.id ? "selected" : "",
                        ].join("")}
                      >
                        {member.name}
                      </Text>
                    </View>
                  );
                })}
              </View>
            </ScrollView>
            <View className="ins">
                {
                  curInsList.length === 0 && <View className="no-ins">
                    <Icon size={60} type='warn'></Icon>
                    <Text className="no-ins-text">暂无保单</Text>
                  </View>
                }
                {curInsList.length > 0 && curInsList.map((ins,index)=>{
                  return (
                    <View key={index} className="ins-item">
                      <View className="ins-info">
                        <Text className="ins-name bold">{ins.productName}</Text>
                        <Text className="ins-status">{ins.orderStatusCN}</Text>
                      </View>
                      <View className="ins-info">
                        <View className="ins-info-left">
                          被保险人：{ins.name}
                        </View>
                        <View className="ins-info-right">
                          保费：{ins.goldCount}万户分
                        </View>
                      </View>

                      <View className="ins-info">
                        <View className="ins-info-left">
                          保障额度：{ins.insuranceCoverage}
                        </View>
                        <View className="ins-info-right">
                          类型：{ getProductTypeName(ins.productType)}
                        </View>
                      </View>

                      <View className="ins-info">
                        <View className="ins-info-right">
                          保障期限：{ins.startDate}- {ins.endDate}
                        </View>
                        
                      </View>
                    </View>
                  )
                })}
                
            </View>
          </ScrollView>
        </View>
      )}
    </View>
  );
}
